package gepetto.reactor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.LinkedList;

public class Acceptor extends SelectHandler {
	private ServerSocket server;
	private InetSocketAddress address;
	private LinkedList<AcceptorListener> listeners;

	public Acceptor(int port) throws IOException {
		super(SelectionKey.OP_ACCEPT);
		this.address = new InetSocketAddress(port);
		this.channel = ServerSocketChannel.open ();
		this.channel.configureBlocking(false);
		this.server = ((ServerSocketChannel) this.channel).socket();
		this.server.bind(this.address);
		listeners = new LinkedList<AcceptorListener> ();
	}

	@Override
	public boolean handleEvent() {
		try {
			SocketChannel connection = ((ServerSocketChannel) this.channel).accept();

			if (connection != null) {
				IOHandler ioh = new IOHandler (connection);
				reactor.register (ioh);
				this.notifyAccept(ioh);
				reactor.register (this);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		
		return true;
	}

	public void addAcceptorListener (AcceptorListener listener) {
		listeners.add(listener);
	}

	public void removeAcceptorListener (AcceptorListener listener) {
		listeners.remove(listener);
	}
	
	public void notifyAccept (IOHandler io) {
		for (Iterator<AcceptorListener> it = listeners.iterator(); it.hasNext(); ) {
			it.next().handleAccept(io);
		}
	}
}